package com.wanban.adutils.tools

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import java.text.SimpleDateFormat
import java.util.*

object Tools {

    fun findActivity(context: Context?): Activity? {
        if (context == null) return null
        if (context is Activity) {
            return context
        }
        return if (context is ContextWrapper) {
            findActivity(context.baseContext)
        } else {
            null
        }
    }

    /**
     * long值转换时分秒
     */
    fun getHMSTime(time: Long): String {
        val timeStr: String?
        val hour: Long?
        var minute: Long?
        val second: Long?
        if (time <= 1000)
            return "00:00:00"
        else {
            val secondTime = time / 1000
            minute = secondTime / 60
            if (minute < 60) {
                second = secondTime % 60
                timeStr = "00:" +unitFormat(minute) + ":" + unitFormat(second)
            } else {
                hour = minute / 60
                if (hour > 99)
                    return "99:59:59"
                minute %= 60
                second = secondTime - (hour * 3600) - (minute * 60)
                timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second)
            }
        }
        return timeStr
    }

    private fun unitFormat(i: Long): String {
        return  if (i in 0..9)
            "0$i"
        else
            i.toString()
    }

    /**
     * 时间戳转换成日期格式字符串
     */
    fun timeStamp2Date(millis: Long): String {
        val format = "yyyy-MM-dd HH:mm:ss"
        val sdf = SimpleDateFormat(format, Locale.getDefault())
        return sdf.format(Date(millis))
    }
}